package com.furschina.struts2;

import java.util.Map;

import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ParameterAware;

import cn.wooshai.core.util.RequestUtil;

public abstract class CaptchaAction extends BaseAction implements ParameterAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -93876415959082817L;
	protected ReCaptcha reCaptcha;
	protected Map<String, String[]> parameters;

	public CaptchaAction() {
		super();
	}

	/**
	 * @param reCaptcha
	 *            the reCaptcha to set
	 */
	public void setReCaptcha(ReCaptcha reCaptcha) {
		this.reCaptcha = reCaptcha;
	}
	
	public void setParameters(Map<String, String[]> parameters) {
		this.parameters = parameters;
	}

	public String getCaptchadiv() {
		return this.reCaptcha.createRecaptchaHtml(null, "clean", null);
	}

	public boolean validateCaptcha() {
		if (this.parameters.get("recaptcha_challenge_field") == null
				|| this.parameters.get("recaptcha_response_field") == null) {
			return false;
		}
		String ip = RequestUtil.getRemoteIp(ServletActionContext.getRequest());
		ReCaptchaResponse response = this.reCaptcha.checkAnswer(
				ip,
				this.parameters.get("recaptcha_challenge_field")[0],
				this.parameters.get("recaptcha_response_field")[0]);
		LOG.info(response.getErrorMessage() + ":" + ip);
		return response.isValid();
	}

}